package vsqlbuilder.gui;

import java.awt.Cursor;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;

public class ToolBarButtonGroup extends ButtonGroup {

	private static final long serialVersionUID = 0L; // TODO [low] This is a
														// temporary solution to
														// warning, should be
														// fixed

	private Map<Integer, Cursor> cursors;

	private Map<Integer, AbstractButton> buttons;

	private List<ActionListener> listeners;

	private Window window;

	public ToolBarButtonGroup(Window window) {

		this.window = window;
		this.cursors = new HashMap<Integer, Cursor>();
		this.buttons = new HashMap<Integer, AbstractButton>();
		this.listeners = new ArrayList<ActionListener>();
	}

	public void add(AbstractButton button, Cursor cursor) {

		super.add(button);
		Integer key = new Integer(button.getMnemonic());
		this.cursors.put(key, cursor);
		this.buttons.put(key, button);
	}

	public void setSelected(ButtonModel buttonModel, boolean selected) {

		super.setSelected(buttonModel, selected);
		if (selected && buttonModel.isSelected()) {
			int mnemonic = buttonModel.getMnemonic();
			Integer key = new Integer(buttonModel.getMnemonic());
			Cursor cursor = this.cursors.get(key);
			this.window.setCursor(cursor);
			AbstractButton button = this.buttons.get(key);

			for (ActionListener listener : this.listeners) {
				ActionEvent event = new ActionEvent(button, mnemonic, button
						.getActionCommand());
				listener.actionPerformed(event);
			}
		}
	}

	public void addActionListener(ActionListener listener) {

		this.listeners.add(listener);
	}
}
